//含拦截器和token
import axios from 'axios';
import router from '../router'
import qs from "qs";
import {
	Loading,
	Message
} from 'element-ui';
import _ from 'lodash';

axios.defaults.timeout = 50000;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.baseURL = '/wsj';
axios.defaults.withCredentials=true;

//loading对象
let loading;

//当前正在请求的数量
let needLoadingRequestCount = 0;

//显示loading
function showLoading(target) {
	// 后面这个判断很重要，因为关闭时加了抖动，此时loading对象可能还存在，
	// 但needLoadingRequestCount已经变成0.避免这种情况下会重新创建个loading
	if (needLoadingRequestCount === 0 && !loading) {
		loading = Loading.service({
			lock: true,
			text: '加载中.....',
			spinner: 'el-icon-loading',
			background: 'rgba(0, 0, 0, 0.2)'
		});
	}
	needLoadingRequestCount++;
}
//隐藏loading
function hideLoading() {
	needLoadingRequestCount--;
	needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); //做个保护
	if (needLoadingRequestCount === 0) {
		//关闭loading
		toHideLoading();
	}
}

//防抖：将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时， loading闪烁的问题。
var toHideLoading = _.debounce(() => {
	if(loading){
		loading.close();
		loading = null;
	}
}, 300);

//http request 拦截器
axios.interceptors.request.use(
	config => {
		config.headers = {
			'Cache-Control': 'no-cache',
			'Content-Type': 'application/json;charset=UTF-8',
		}
		const token = localStorage.getItem('token') == null ? '' : localStorage.getItem('token');
		token && (config.headers.Authorization = 'bearer ' + token);
		return config;
	},
	error => {
		//判断当前请求是否设置了不显示Loading
		if (config.headers.showLoading !== false) {
			hideLoading();
		}
		return Promise.reject(error);
	}
);

axios.interceptors.response.use(
	response => {
		//判断当前请求是否设置了不显示Loading（不显示自然无需隐藏）
		if (response.config.headers.showLoading !== false) {
			hideLoading();
		}
		if (response.status === 200) {
			return Promise.resolve(response);
		} else {
			//判断当前请求是否设置了不显示Loading（不显示自然无需隐藏）
			if (response.config.headers.showLoading !== false) {
				hideLoading();
			}
			return Promise.reject(response);
		}
	},
	error => {
		//判断当前请求是否设置了不显示Loading（不显示自然无需隐藏）
		hideLoading();
		if (error.response) {
			if (error.response.status === 404) {
				localStorage.clear();
				//router.replace('/404');
			}
		}
		if (error.response) {
			if (error.response.status === 401) {
				Message.error('你还没有权限');
				/* localStorage.clear();
				router.replace('/'); */
			}
		}
		if (error.response) {
			if (error.response.status === 500) {
				Message.error('服务器错误，请联系技术人员处理！');
			}
		}
		if (error.response) {
			if (error.response.status === 403) {
				Message.error('密码错误！');
				router.replace('/');
			}
		}
		return Promise.reject(error)
	}
);


export default {
	/**
	 * 封装get方法
	 * @param url
	 * @param data
	 * @returns {Promise}
	 */
	get: function(url, params = {}) {
		return new Promise((resolve, reject) => {
			axios.get(url, {
					params: params
				})
				.then(response => {
					resolve(response.data)
				})
				.catch(err => {
					reject(err)
				})
		})
	},
	/**
	 * 封装post请求
	 * @param url
	 * @param data
	 * @returns {Promise}
	 */
	post: function(url, data, config = {}) {
		return new Promise((resolve, reject) => {
			axios.post(url, data, config)
				.then(response => {
					resolve(response.data)
				}, err => {
					reject(err)
				})
		})
	},
	/**
	 * 封装put请求
	 * @param url
	 * @param data
	 * @returns {Promise}
	 */
	put: function(url, data) {
		return new Promise((resolve, reject) => {
			axios.put(url, data)
				.then(response => {
					resolve(response.data)
				}, err => {
					reject(err)
				})
		})
	},
	/**
	 * 封装delete请求
	 * @param url
	 * @param data
	 * @returns {Promise}
	 */
	delete: function(url, params = {}) {
		return new Promise((resolve, reject) => {
			axios.delete(url, {
					params: params
				})
				.then(response => {
					resolve(response.data)
				}, err => {
					reject(err)
				})
		})
	},
	/**
	 * 封装patch请求
	 * @param url
	 * @param params
	 * @returns {Promise}
	 */
	patch: function(url) {
		return new Promise((resolve, reject) => {
			axios.patch(url)
				.then(response => {
					resolve(response.data)
				})
				.catch(err => {
					reject(err)
				})
		})
	},
}
